<template>
  <div id="app">
    <div class="info-out-box">
      <div class="info-title">
        <div class="info-title_name">设置</div>
        <div class="win-ctrl">
          <div class="btn info_min" @click="handleWindowMin"></div>
          <div class="btn info_close" @click="handleWindowClose"></div>
        </div>
      </div>
      <div class="info-content">
        <div class="left">
          <div class="item">个人资料设置</div>
        </div>
        <div class="right">
          <div class="right-content">
            <div class="userInfo_content">
              <div class="title">个人资料设置</div>
              <div class="item">
                <div class="label">头像：</div>
                <div class="value">
                  <avatar class="userInfo_tx" :src="userInfo.tx" @click="handleAvatarClick"></avatar>
                </div>
              </div>
              <div class="item">
                <div class="label">用户名：</div>
                <div class="value">
                  <input v-model="userInfo.xm">
                </div>
              </div>
              <div class="item">
                <div class="label">签名：</div>
                <div class="value">
                  <input v-model="userInfo.qm">
                </div>
              </div>
              <div class="item">
                <div class="label">网卡：</div>
                <div class="value">
                  <select v-model="selectMac">
                    <option :value="item.mac" :key="index" v-for="(item,index) in networkInfos">
                      {{item.name}}({{item.address}})
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
          <div class="btn-box">
            <div class="btn info_conform" @click="handleConfirmClick">确定</div>
            <div class="btn info_cancel" @click="handleCancelClick">取消</div>
          </div>
        </div>
      </div>
    </div>
    <div class="ghtx-box" v-show="changeAvatarBoxShow">
      <div class="ghtx-in-box">
        <div class="ghtx-title">
          <div class="close" @click="changeAvatarBoxShow=false"></div>
        </div>
        <div class="avatar-box">
          <div id="avatar-container"></div>
        </div>
        <div class="toolbar">
          <div class="btn narrow" @click="zoomout"></div>
          <input type="range" v-model="scale" min="1" step="0.1" max="3.1">
          <div class="btn enlarge" @click="zoomin"></div>
          <div class="btn clockwise"></div>
          <div class="btn counterclockwise"></div>
        </div>
        <div class="btn-box">
          <div class="btn" @click="changeAvatar">选择图片</div>
          <div class="btn" @click="handleChangeAvatarConfirmClick">确定</div>
          <div class="btn" @click="changeAvatarBoxShow=false">取消</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapState} from 'vuex'
  import Avatar from '../../components/Avatar'
  import Konva from 'konva'

  const fs = require('fs')
  const path = require('path')
  const userUtil = require('../../util/userUtil')
  const commonUtil = require('../../util/commonUtil')
  // const Konva = require('konva')

  export default {
    name: 'set-page',
    components: {Avatar},
    data () {
      return {
        win: null,
        scale: 1,
        networkInfos: commonUtil.getNetworkInfos(),
        changeAvatarBoxShow: false,
        selectMac: '',
        userInfo: {}
      }
    },
    computed: {
      ...mapState({
        setWindowShow: state => state.setWindowShow
      }),
      ...mapGetters(['getUserInfoByUserip'])
    },
    watch: {
      async setWindowShow () {
        if (this.setWindowShow) {
          this.userInfo = JSON.parse(JSON.stringify(this.getUserInfoByUserip(commonUtil.getNetworkInfo().address)))
          this.win.show()
        } else {
          this.win.hide()
        }
      },
      scale () {
        if (typeof this.scale === 'number') {
          let image = this.layer.findOne('#img')
          let img = image.image()
          let initScale = Math.min(img.width / 350, img.height / 350)
          let cousomScale = initScale / this.scale
          if (image) {
            let cropSize = 350 * cousomScale
            let cropX = image.crop().x
            let cropY = image.crop().y
            if (cropX + cropSize > img.width) cropX = img.width - cropSize
            if (cropY + cropSize > img.height) cropY = img.height - cropSize
            image.setAttrs({
              cousomScale: cousomScale,
              crop: {
                x: cropX,
                y: cropY,
                width: cropSize,
                height: cropSize
              }
            })
          }
          this.layer.draw()
        } else {
          this.scale = Number(this.scale)
        }
      }
    },
    async created () {
      this.win = this.$electron.remote.getCurrentWindow()
      if (this.networkInfos.length) this.selectMac = myStorage.getItem('selectMac', this.networkInfos[0].mac)
    },
    mounted () {
      // let avatarContainer = document.getElementById('avatar-container')
      let stage = new Konva.Stage({
        container: 'avatar-container',
        width: 350,
        height: 350
      })
      this.layer = new Konva.Layer()
      stage.add(this.layer)
      let startX = 0
      let startY = 0
      let image = new Konva.Image({
        id: 'img',
        width: 350,
        height: 350,
        cousomScale: 1,
        crop: {
          x: 0,
          y: 0,
          width: 350,
          height: 350
        },
        draggable: true,
        dragBoundFunc: pos => {
          let cousomScale = image.getAttr('cousomScale')
          let deltaX = pos.x * cousomScale
          let deltaY = pos.y * cousomScale
          let x = startX - deltaX
          let y = startY - deltaY
          let img = image.image()
          let crop = image.crop()

          let maxX = img.width - crop.width
          let maxY = img.height - crop.height

          if (x < 0) {
            x = 0
          } else if (x > maxX) x = maxX
          if (y < 0) {
            y = 0
          } else if (y > maxY) y = maxY

          image.setAttr('crop', {
            x: x,
            y: y
          })
          this.layer.draw()
          return {
            x: 0,
            y: 0
          }
        }
      })
      image.on('dragstart', evt => {
        let crop = image.crop()
        startX = crop.x
        startY = crop.y
      })
      let mask = new Konva.Path({
        height: 350,
        width: 350,
        data: `m0,0l350,0l0,350l-350,0l0,-350m175,175m-175,0a175,175 0 1 0 350,0a175,175 0 1 0 -350,0`,
        fill: 'rgba(0,0,0,0.5)',
        listening: false
      })
      this.layer.add(image).add(mask).draw()
    },
    methods: {
      zoomout () {
        this.scale = Number(this.scale)
        if (this.scale > 1) this.scale -= 0.1
      },
      zoomin () {
        if (this.scale < 3.1) this.scale += 0.1
      },
      // handleRangeChange () {
      //   console.log(this.scale)
      // },
      handleAvatarClick () {
        this.changeAvatarBoxShow = true

        let img = new Image()
        img.src = this.userInfo.tx
        img.onload = () => {
          let image = this.layer.findOne('#img')
          if (image) {
            let scale = Math.min(img.width / 350, img.height / 350)
            image.setAttrs({
              cousomScale: scale,
              image: img,
              crop: {
                width: 350 * scale,
                height: 350 * scale
              }
            })
          }
          this.layer.draw()
        }
      },
      changeAvatar () {
        let res = this.$electron.remote.dialog.showOpenDialog(this.$electron.remote.getCurrentWindow(), {
          filters: [{
            name: '图片',
            extensions: ['png', 'jpeg', 'jpg']
          }]
        })
        if (!res) return
        let extname = path.extname(res[0]).replace('.', '')
        let imgStr = fs.readFileSync(res[0]).toString('base64')
        let imgsrc = `data:image/${extname};base64,${imgStr}`
        let img = new Image()
        img.src = imgsrc
        img.onload = () => {
          let image = this.layer.findOne('#img')
          if (image) {
            let scale = Math.min(img.width / 350, img.height / 350)
            image.setAttrs({
              cousomScale: scale,
              image: img,
              crop: {
                x: 0,
                y: 0,
                width: 350 * scale,
                height: 350 * scale
              }
            })
          }
          this.layer.draw()
        }
      },
      handleChangeAvatarConfirmClick () {
        let image = this.layer.findOne('#img')
        if (image) {
          this.userInfo.tx = image.toDataURL()
          this.changeAvatarBoxShow = false
        }
      },
      async handleConfirmClick () {
        // 保存用户资料
        await userUtil.updateUser(this.userInfo)
        myStorage.setItem('selectMac', this.selectMac)
        myStorage.setItem('communication', {
          action: 'sendMsg',
          data: {
            sendData: JSON.stringify({action: 'update-info', data: this.userInfo}),
            sendIp: commonUtil.getNetworkInfo().broadcastAddress
          }
        })
        myStorage.setItem('mineInfo', this.userInfo)
        this.win.close()
      },
      handleCancelClick () {
        this.win.close()
      },
      handleWindowMin () {
        this.win.minimize()
      },
      handleWindowClose () {
        this.win.close()
      }
    }
  }
</script>

<style>
  html, body {
    margin: 0;
    padding: 0;
    cursor: default;
    user-select: none;
    height: 100vh;
    width: 100vw;
  }
</style>
<style scoped lang="scss">
  #app {
    height: 100%;
    width: 100%;

    .info-out-box {
      height: 100%;

      .info-title {
        height: 30px;
        /*background-color: #2c3e50;*/
        -webkit-app-region: drag;
        position: relative;
        border-bottom: 1px solid #dddddd;
        box-sizing: border-box;

        .info-title_name {
          height: 30px;
          font-size: 14px;
          font-weight: bold;
          line-height: 30px;
          margin-left: 10px;
        }

        .win-ctrl {
          position: absolute;
          right: 0;
          top: 0;
          font-size: 0;

          .info_min {
            background: url("../../assets/suoxiao.png") no-repeat center;
            background-size: 50%;

            &:hover {
              background: url("../../assets/suoxiao-1.png") no-repeat center;
              background-size: 50%;
            }
          }

          .info_close {
            background: url("../../assets/closeaj.png") no-repeat center;
            background-size: 50%;

            &:hover {
              background: url("../../assets/closeaj-1.png") no-repeat center;
              background-size: 50%;
            }
          }

          .btn {
            width: 30px;
            height: 30px;
            display: inline-block;
            /*background-color: #42b983;*/
            -webkit-app-region: no-drag;

            &:hover {
              background-color: #cccccc;
            }
          }
        }
      }

      .info-content {
        height: calc(100% - 30px);
        font-size: 0;

        .left {
          display: inline-block;
          width: 200px;
          /*background-color: #42b983;*/
          height: 100%;
          box-sizing: border-box;
          vertical-align: top;
          box-sizing: border-box;
          border-right: 1px solid #dddddd;

          .item {
            font-size: 14px;
            line-height: 30px;
            text-indent: 20px;

            &:hover {
              background-color: #cccccc;
            }
          }
        }

        .right {
          display: inline-block;
          width: calc(100% - 200px);
          height: 100%;
          box-sizing: border-box;
          padding: 6px;
          /*background-color: #c3d9ff;*/

          .right-content {
            height: calc(100% - 30px);

            .userInfo_content {
              padding: 5px;
              box-sizing: border-box;
              width: 100%;

              .title {
                font-size: 24px;
                width: 100%;
                height: 30px;
                line-height: 30px;
                font-weight: bold;
                border: 1px solid #dddddd;
              }

              .item {
                /*margin-bottom: 10px;*/
                $label_width: 100px;
                height: 60px;
                position: relative;

                .label {
                  font-size: 14px;
                  width: $label_width;
                  float: left;
                  height: 60px;
                  line-height: 60px;
                  text-align: right;
                }

                .value {
                  display: inline-block;
                  width: calc(100% - #{$label_width});
                  height: 100%;

                  .userInfo_tx {
                    margin-top: 10px;
                  }

                  input {
                    height: 20px;
                    position: absolute;
                    top: 0;
                    bottom: 0;
                    margin: auto;
                  }

                  select {
                    font-size: 14px;
                  }
                }
              }
            }
          }


          .btn-box {
            height: 30px;
            text-align: center;

            .info_conform {
              background: #f7c380;
            }

            .btn {
              display: inline-block;
              font-size: 14px;
              /*background-color: #42b983;*/
              margin-left: 10px;
              padding: 3px 15px;
              border-radius: 3px;
              font-size: 14px;
              border: 1px solid #dddddd;

              &:nth-child(1) {
                margin-left: 0;
              }
            }
          }
        }
      }
    }

    .ghtx-box {
      position: fixed;
      top: 30px;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: rgba(0, 0, 0, 0.1);

      .ghtx-in-box {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        height: 450px;
        width: 380px;
        background-color: white;

        .ghtx-title {
          height: 30px;
          position: relative;

          .close {
            position: absolute;
            top: 0;
            right: 0;
            height: 30px;
            width: 30px;
            background: url("../../assets/closeaj.png") no-repeat center;
            background-size: 50%;

            &:hover {
              background: url("../../assets/closeaj-1.png") no-repeat center;
              background-size: 50%;
            }
          }
        }

        .avatar-box {
          height: 350px;
          width: 350px;
          margin: 0 auto;
          background-color: #cccccc;

          #avatar-container {
            height: 100%;
            width: 100%;
          }
        }

        .toolbar {
          height: 40px;
          padding: 0 15px;
          font-size: 0;

          input[type=range] {
            -webkit-appearance: none;
            width: calc(100% - 139px);
            height: 100%;
            vertical-align: top;
            outline: none;

            &::-webkit-slider-runnable-track {
              height: 3px;
              border-radius: 3px; /*将轨道设为圆角的*/
              background-color: #bbbbbb;
              /*box-shadow: 0 1px 1px #def3f8, inset 0 .125em .125em #0d1112; !*轨道内置阴影效果*!*/
            }

            &::-webkit-slider-thumb {
              -webkit-appearance: none;
              height: 10px;
              width: 10px;
              margin-top: -4px; /*使滑块超出轨道部分的偏移量相等*/
              background-color: #f7c380;
              border-radius: 50%; /*外观设置为圆形*/
              /*border: solid 0.125em rgba(205, 224, 230, 0.5); !*设置边框*!*/
              /*box-shadow: 0 .125em .125em #3b4547; !*添加底部阴影*!*/
            }

            & + .btn {
              margin-right: 5px;
            }
          }

          .btn {
            display: inline-block;
            height: 30px;
            width: 30px;
            margin-top: 5px;
            /*background-color: #cccccc;*/

            & + .btn {
              margin-left: 5px;
            }
          }

          .narrow {
            background: url("../../assets/narrow.png") no-repeat center;
            background-size: 80%;

            &:hover {
              background: url("../../assets/narrow-1.png") no-repeat center;
              background-size: 80%;
            }
          }

          .enlarge {
            background: url("../../assets/enlarge.png") no-repeat center;
            background-size: 80%;

            &:hover {
              background: url("../../assets/enlarge-1.png") no-repeat center;
              background-size: 80%;
            }
          }

          .clockwise {
            background: url("../../assets/clockwise.png") no-repeat center;
            background-size: 80%;

            &:hover {
              background: url("../../assets/clockwise-1.png") no-repeat center;
              background-size: 80%;
            }
          }

          .counterclockwise {
            background: url("../../assets/counterclockwise.png") no-repeat center;
            background-size: 80%;

            &:hover {
              background: url("../../assets/counterclockwise-1.png") no-repeat center;
              background-size: 80%;
            }
          }
        }

        .btn-box {
          text-align: right;
          height: 30px;
          font-size: 0;
          background-color: #f5f6f8;

          .btn {
            display: inline-block;
            margin-top: 5px;
            height: 20px;
            font-size: 14px;
            background-color: #f7c380;
            margin-right: 10px;
            line-height: 20px;
            padding: 0 20px;
            color: #666;
            border-radius: 3px;
          }
        }
      }
    }
  }
</style>
